import { createStore } from 'vuex'
import axios from 'axios'

// API基础URL
const API_URL = 'http://localhost:8000/api/v1'

// 创建axios实例
const api = axios.create({
  baseURL: API_URL,
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器添加token
api.interceptors.request.use(config => {
  const token = localStorage.getItem('token')
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
})

export default createStore({
  state: {
    user: null,
    token: localStorage.getItem('token') || null,
    projects: [],
    currentProject: null,
    tasks: [],
    documents: [],
    notifications: [],
    loading: false,
    error: null
  },
  getters: {
    isAuthenticated: state => !!state.token,
    currentUser: state => state.user,
    userProjects: state => state.projects,
    projectTasks: state => state.tasks,
    projectDocuments: state => state.documents,
    userNotifications: state => state.notifications,
    isLoading: state => state.loading,
    hasError: state => !!state.error,
    errorMessage: state => state.error
  },
  mutations: {
    SET_USER(state, user) {
      state.user = user
    },
    SET_TOKEN(state, token) {
      state.token = token
      localStorage.setItem('token', token)
    },
    CLEAR_AUTH(state) {
      state.user = null
      state.token = null
      localStorage.removeItem('token')
    },
    SET_PROJECTS(state, projects) {
      state.projects = projects
    },
    SET_CURRENT_PROJECT(state, project) {
      state.currentProject = project
    },
    SET_TASKS(state, tasks) {
      state.tasks = tasks
    },
    SET_DOCUMENTS(state, documents) {
      state.documents = documents
    },
    SET_NOTIFICATIONS(state, notifications) {
      state.notifications = notifications
    },
    SET_LOADING(state, status) {
      state.loading = status
    },
    SET_ERROR(state, error) {
      state.error = error
    },
    CLEAR_ERROR(state) {
      state.error = null
    }
  },
  actions: {
    // 用户认证相关
    async login({ commit }, credentials) {
      commit('SET_LOADING', true)
      commit('CLEAR_ERROR')
      try {
        const response = await api.post('/auth/login/access-token', credentials)
        const { access_token, user } = response.data
        commit('SET_TOKEN', access_token)
        commit('SET_USER', user)
        return user
      } catch (error) {
        commit('SET_ERROR', error.response?.data?.detail || '登录失败')
        throw error
      } finally {
        commit('SET_LOADING', false)
      }
    },
    async register({ commit }, userData) {
      commit('SET_LOADING', true)
      commit('CLEAR_ERROR')
      try {
        const response = await api.post('/users', userData)
        return response.data
      } catch (error) {
        commit('SET_ERROR', error.response?.data?.detail || '注册失败')
        throw error
      } finally {
        commit('SET_LOADING', false)
      }
    },
    async fetchUserProfile({ commit }) {
      commit('SET_LOADING', true)
      try {
        const response = await api.get('/users/me')
        commit('SET_USER', response.data)
        return response.data
      } catch (error) {
        commit('SET_ERROR', error.response?.data?.detail || '获取用户信息失败')
        throw error
      } finally {
        commit('SET_LOADING', false)
      }
    },
    logout({ commit }) {
      commit('CLEAR_AUTH')
    },
    
    // 项目相关
    async fetchProjects({ commit }) {
      commit('SET_LOADING', true)
      try {
        const response = await api.get('/projects')
        commit('SET_PROJECTS', response.data)
        return response.data
      } catch (error) {
        commit('SET_ERROR', error.response?.data?.detail || '获取项目列表失败')
        throw error
      } finally {
        commit('SET_LOADING', false)
      }
    },
    async fetchProjectById({ commit }, projectId) {
      commit('SET_LOADING', true)
      try {
        const response = await api.get(`/projects/${projectId}`)
        commit('SET_CURRENT_PROJECT', response.data)
        return response.data
      } catch (error) {
        commit('SET_ERROR', error.response?.data?.detail || '获取项目详情失败')
        throw error
      } finally {
        commit('SET_LOADING', false)
      }
    },
    async createProject({ commit }, projectData) {
      commit('SET_LOADING', true)
      try {
        const response = await api.post('/projects', projectData)
        return response.data
      } catch (error) {
        commit('SET_ERROR', error.response?.data?.detail || '创建项目失败')
        throw error
      } finally {
        commit('SET_LOADING', false)
      }
    },
    
    async updateProject({ commit }, { id, data }) {
      commit('SET_LOADING', true)
      try {
        const response = await api.put(`/projects/${id}`, data)
        return response.data
      } catch (error) {
        commit('SET_ERROR', error.response?.data?.detail || '更新项目失败')
        throw error
      } finally {
        commit('SET_LOADING', false)
      }
    },
    
    async deleteProject({ commit }, projectId) {
      commit('SET_LOADING', true)
      try {
        const response = await api.delete(`/projects/${projectId}`)
        return response.data
      } catch (error) {
        commit('SET_ERROR', error.response?.data?.detail || '删除项目失败')
        throw error
      } finally {
        commit('SET_LOADING', false)
      }
    },
    
    // 任务相关
    async fetchTasks({ commit }, filters = {}) {
      commit('SET_LOADING', true)
      try {
        const response = await api.get('/tasks', { params: filters })
        commit('SET_TASKS', response.data)
        return response.data
      } catch (error) {
        commit('SET_ERROR', error.response?.data?.detail || '获取任务列表失败')
        throw error
      } finally {
        commit('SET_LOADING', false)
      }
    },
    async createTask({ commit }, taskData) {
      commit('SET_LOADING', true)
      try {
        const response = await api.post('/tasks', taskData)
        return response.data
      } catch (error) {
        commit('SET_ERROR', error.response?.data?.detail || '创建任务失败')
        throw error
      } finally {
        commit('SET_LOADING', false)
      }
    },
    
    // 阶段相关
    async fetchPhases({ commit }, projectId) {
      commit('SET_LOADING', true)
      try {
        const response = await api.get(`/projects/${projectId}/phases`)
        return response.data
      } catch (error) {
        commit('SET_ERROR', error.response?.data?.detail || '获取阶段列表失败')
        throw error
      } finally {
        commit('SET_LOADING', false)
      }
    },
    
    // 里程碑相关
    async fetchMilestones({ commit }, projectId) {
      commit('SET_LOADING', true)
      try {
        const response = await api.get(`/projects/${projectId}/milestones`)
        return response.data
      } catch (error) {
        commit('SET_ERROR', error.response?.data?.detail || '获取里程碑列表失败')
        throw error
      } finally {
        commit('SET_LOADING', false)
      }
    },
    
    // 用户相关
    async fetchUsers({ commit }) {
      commit('SET_LOADING', true)
      try {
        const response = await api.get('/users')
        return response.data
      } catch (error) {
        commit('SET_ERROR', error.response?.data?.detail || '获取用户列表失败')
        throw error
      } finally {
        commit('SET_LOADING', false)
      }
    },
    
    // 文档相关
    async fetchDocuments({ commit }, filters = {}) {
      commit('SET_LOADING', true)
      try {
        const response = await api.get('/documents', { params: filters })
        commit('SET_DOCUMENTS', response.data)
        return response.data
      } catch (error) {
        commit('SET_ERROR', error.response?.data?.detail || '获取文档列表失败')
        throw error
      } finally {
        commit('SET_LOADING', false)
      }
    },
    async uploadDocument({ commit }, { formData, config }) {
      commit('SET_LOADING', true)
      try {
        const response = await api.post('/documents/upload', formData, config)
        return response.data
      } catch (error) {
        commit('SET_ERROR', error.response?.data?.detail || '上传文档失败')
        throw error
      } finally {
        commit('SET_LOADING', false)
      }
    },
    
    // 通知相关
    async fetchNotifications({ commit }) {
      commit('SET_LOADING', true)
      try {
        const response = await api.get('/notifications')
        commit('SET_NOTIFICATIONS', response.data)
        return response.data
      } catch (error) {
        commit('SET_ERROR', error.response?.data?.detail || '获取通知失败')
        throw error
      } finally {
        commit('SET_LOADING', false)
      }
    },
    async markNotificationAsRead({ commit }, notificationId) {
      try {
        const response = await api.put(`/notifications/${notificationId}/read`)
        return response.data
      } catch (error) {
        commit('SET_ERROR', error.response?.data?.detail || '标记通知已读失败')
        throw error
      }
    }
  },
  modules: {
  }
})